<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>表单验证</title>
    <style>
    input {
        width: 200px;
        height: 16px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.42857143;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        /*        outline: none;*/
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    }
    
    .btn {
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        -ms-touch-action: manipulation;
        touch-action: manipulation;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-image: none;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    
    .btn-primary {
        color: #fff;
        background-color: #337ab7;
        border-color: #2e6da4;
    }
    
    .validate_message {
        font-size: 16px;
        color: #B4B4B4;
    }
    
    .bsuccess {
        border-color: #5cb85c!important;
    }
    
    .bdanger {
        border-color: #d9534f!important;
    }
    
    .success {
        color: #5cb85c!important;
    }
    
    .danger {
        color: #d9534f!important;
    }
    </style>
</head>

<body>

    <body>
        <form action="">
            <div class="form">
                名称&ensp;&ensp;&ensp;&ensp;&ensp;
                <input type="text" id="name">
                <p id="nameMessage" class="validate_message"></p>
                密码&ensp;&ensp;&ensp;&ensp;&ensp;
                <input type="password" id="password">
                <p id="passwordMessage" class="validate_message"></p>
                密码确认&ensp;
                <input type="password" id="verifypass">
                <p id="verifypassMessage" class="validate_message"></p>
                邮箱&ensp;&ensp;&ensp;&ensp;&ensp;
                <input type="text" id="email">
                <p id="emailMessage" class="validate_message"></p>
                手机&ensp;&ensp;&ensp;&ensp;&ensp;
                <input type="text" id="phone">
                <p id="phoneMessage" class="validate_message"></p>
            </div>
            <div id="verify" class="btn btn-primary">提交</div>
        </form>
    </body>
    <script>
    //对每个控件绑定获得焦点事件

    document.querySelector("#name").addEventListener('focus', function() {
        ruleMessage('nameMessage', 'name');
    }, false);
    document.querySelector("#password").addEventListener('focus', function() {
        ruleMessage('passwordMessage', 'password');
    }, false);
    document.querySelector("#verifypass").addEventListener('focus', function() {
        ruleMessage('verifypassMessage', 'verifypass');
    }, false);
    document.querySelector("#email").addEventListener('focus', function() {
        ruleMessage('emailMessage', 'email');
    }, false);
    document.querySelector("#phone").addEventListener('focus', function() {
        ruleMessage('phoneMessage', 'phone');
    }, false);


    //对每个控件绑定失去焦点事件
    document.querySelector("#name").addEventListener('blur', function() {
        validate('checkName');
    }, false);
    document.querySelector("#password").addEventListener('blur', function() {
        validate('checkPassword');
    }, false);
    document.querySelector("#verifypass").addEventListener('blur', function() {
        validate('verifyPassword');
    }, false);
    document.querySelector("#email").addEventListener('blur', function() {
        validate('checkEmail');
    }, false);
    document.querySelector("#phone").addEventListener('blur', function() {
        validate('checkPhone');
    }, false);

    var submit = document.querySelector("#verify");
    submit.addEventListener('click', function() {
        validate('checkAll');
    }, false);

    //传入target，type
    function ruleMessage(target, type) {
        // 对提醒消息样式进行更改
        var message = '';
        switch (type) {
            case 'name':
                message = '必填,长度为4-16个字符';
                break;
            case 'password':
                message = '必填,请输入4位或以上的密码';
                break;
            case 'verifypass':
                message = '再次输入相同密码';
                break;
            case 'email':
                message = '必填,请输入正确格式的邮箱';
                break;
            case 'phone':
                message = '必填,请输入11位手机号码';
                break;
        }
        //对输入框样式进行修改
        document.querySelector("#" + target).className = 'validate_message';

        document.querySelector("#" + target).innerText = message;
    }

    function validate(type) {
        function checkLen(type, name) {
            var validated = document.querySelector("#" + type).value;
            var len = 0;
            var status = 1; //1是成功，0是失败
            var message = name + '可用'; //默认成功消息
            var result = [];
            for (var i = validated.length - 1; i >= 0; i--) {
                //汉字长度为2
                if (/^[\u4e00-\u9fa5]+$/.test(validated[i])) {
                    len = len + 2;
                } else {
                    len++;
                }

            }
            if (len < 4 || len > 16) {
                message = "长度必须为4~16个字符";
                status = 0;
            }
            if (len == 0) {
                message = name + "不能为空";
                status = 0;
            }

            result.push(message);
            result.push(status);
            return result;
        }

        function passRe() {
            //获取两次输入的密码
            var previous = document.querySelector("#password").value;
            var validated = document.querySelector("#verifypass").value;
            var status = 1; //1是成功，0是失败
            var message = '密码输入一致';
            var result = [];

            if (validated != previous) {
                message = "密码输入不一致,请重新输入";
                status = 0;
            }

            if (validated == '') {
                message = "密码不能为空";
                status = 0;
            }

            if (checkLen('password', "密码")[1] != 1) {
                message = "前面的密码不合法";
                status = 0;
            }

            result.push(message);
            result.push(status);
            return result;

        }

        function regex(type, name, regex) {
            var validated = document.querySelector("#" + type).value;
            var message = name + '格式正确';
            var status = 1; //1是成功，0是失败
            var result = [];
            if (!regex.test(validated)) {
                message = name + "格式错误";
                status = 0;
            }

            if (validated == '') {
                message = name + "内容不能为空";
                status = 0;
            }
            result.push(message);
            result.push(status);
            return result;
        }
        var check = {
            checkName: function() {
                return showResult('name', checkLen('name', "姓名"));
            },
            checkPassword: function() {
                return showResult('password', checkLen('password', "密码"));
            },

            verifyPassword: function() {
                return showResult('verifypass', passRe());
            },
            checkEmail: function() {
                return showResult('email', regex('email', '邮箱', /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/));
            },
            checkPhone: function() {
                return showResult('phone', regex('phone', '手机', /^0?1[3|4|5|8][0-9]\d{8}$/));
            },
        }

        function checkAll() {
            if (checkLen('name', "姓名")[1] &&
                checkLen('password', "密码")[1] &&
                passRe()[1] &&
                regex('email', '邮箱', /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)[1] &&
                regex('phone', '手机', /^0?1[3|4|5|8][0-9]\d{8}$/)[1] == 1
            ) {
                alert("提交成功!")
            } else {
                alert("提交失败!");
            }
        }

        if (type != 'checkAll') {
            return check[type]();
        } else {
            return checkAll();
        }

    }

    function showResult(type, result) {
        // 对提醒消息样式进行更改
        document.querySelector("#" + type + "Message").innerText = result[0];
        document.querySelector("#" + type + "Message").className = result[1] == 1 ? 'success' : 'danger';

        //对输入框样式进行修改
        document.querySelector("#" + type).className = result[1] == 1 ? 'bsuccess' : 'bdanger';
        return result[1];
    }
    </script>

</html>
